﻿Imports System.Threading
Imports System.Web
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Entities.Users

Namespace DotNetNuke.Modules.ActiveForums
    Public Class UserController
        Friend Shared Function GetUserIdByUserName(ByVal PortalId As Integer, ByVal UserName As String) As Integer
            Try
                Dim user As DotNetNuke.Entities.Users.UserInfo = DotNetNuke.Entities.Users.UserController.GetUserByName(PortalId, UserName)
                If Not user Is Nothing Then
                    Return user.UserID
                Else
                    Return -1
                End If
            Catch ex As Exception
                Return -1

            End Try

            Return -1
        End Function
        Public Function GetUser(ByVal SiteId As Integer, ByVal ModuleId As Integer) As User
            Dim u As User = Nothing
            If Thread.CurrentPrincipal.Identity.IsAuthenticated Then
                If (HttpContext.Current Is Nothing) Then
                    u = DNNGetCurrentUser(SiteId, ModuleId)
                ElseIf Not (HttpContext.Current.Items("AFUserInfo")) Is Nothing Then
                    u = CType(HttpContext.Current.Items("AFUserInfo"), User)
                Else
                    u = DNNGetCurrentUser(SiteId, ModuleId)
                End If
                If Not u Is Nothing Then
                    If HttpContext.Current.Items("AFUserInfo") Is Nothing Then
                        HttpContext.Current.Items.Add("AFUserInfo", u)
                    End If

                End If
                Return u
            Else
                Return New User
            End If
        End Function
        Public Function DNNGetCurrentUser(ByVal SiteId As Integer, ByVal ModuleId As Integer) As User
            Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings()
            Dim u As New User
            Dim cu As DotNetNuke.Entities.Users.UserInfo = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo()
            u = LoadUser(cu)

            u = FillProfile(SiteId, ModuleId, u)
            Dim fc As New ForumController
            Dim fs As String = fc.GetForumsForUser(u.UserRoles, SiteId, ModuleId, "CanApprove")
            If Not String.IsNullOrEmpty(fs) Then
                u.Profile.IsMod = True
            Else
                u.Profile.IsMod = False
            End If


            Return u
        End Function
        Private Function GetDNNUser(ByVal SiteId As Integer, ByVal ModuleId As Integer, ByVal userId As Integer) As User
            Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings()
            Dim u As New User
            Dim uc As New DotNetNuke.Entities.Users.UserController
            Dim dnnUser As DotNetNuke.Entities.Users.UserInfo = uc.GetUser(_portalSettings.PortalId, userId)
            u = LoadUser(dnnUser)
            Return u
        End Function
        Public Function GetDNNUser(ByVal SiteId As Integer, ByVal ModuleId As Integer, ByVal userName As String) As User
            Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings()
            Dim u As New User
            Dim dnnUser As DotNetNuke.Entities.Users.UserInfo = DotNetNuke.Entities.Users.UserController.GetUserByName(_portalSettings.PortalId, userName)
            u = LoadUser(dnnUser)
            Return u
        End Function
        Public Function GetUser(ByVal SiteId As Integer, ByVal ModuleId As Integer, ByVal userId As Integer) As User
            Dim u As User = GetDNNUser(SiteId, ModuleId, userId)
            If Not u Is Nothing Then
                u = FillProfile(SiteId, ModuleId, u)
                Dim fc As New ForumController
                Dim fs As String = fc.GetForumsForUser(u.UserRoles, SiteId, ModuleId, "CanApprove")
                If Not String.IsNullOrEmpty(fs) Then
                    u.Profile.IsMod = True
                Else
                    u.Profile.IsMod = False
                End If
            End If
            Return u
        End Function
        Public Function GetUser(ByVal SiteId As Integer, ByVal ModuleId As Integer, ByVal userName As String) As User
            Dim u As User = GetDNNUser(SiteId, ModuleId, userName)
            If Not u Is Nothing Then
                u = FillProfile(SiteId, ModuleId, u)
                Dim fc As New ForumController
                Dim fs As String = fc.GetForumsForUser(u.UserRoles, SiteId, ModuleId, "CanApprove")
                If Not String.IsNullOrEmpty(fs) Or u.IsSuperUser Or u.IsAdmin Then
                    u.Profile.IsMod = True
                Else
                    u.Profile.IsMod = False
                End If
            End If
            Return u
        End Function
        Public Function FillProfile(ByVal SiteId As Integer, ByVal ModuleId As Integer, ByVal u As User) As User
            If Not u Is Nothing AndAlso u.UserId > 0 Then
                u.Profile = Profiles_Get(SiteId, ModuleId, u.UserId)
            End If
            Return u
        End Function
        ' KR - added caching to profiles to skip the DB hit
        Public Function Profiles_Get(ByVal SiteId As Integer, ByVal InstanceId As Integer, ByVal UserId As Integer) As UserProfileInfo

            Dim cachekey As String = String.Format("AF-prof-{0}-{1}-{2}", UserId, SiteId, InstanceId)
            Dim dt As DataTable
            Dim row As DataRow
            Dim upi As UserProfileInfo = Nothing
            Dim db As New Data.Profiles
            Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings()
            If SiteId = -1 Then
                SiteId = _portalSettings.PortalId
            End If

            ' see if it's in cache already
            Dim data As Object = DataCache.CacheRetrieve(cachekey)

            If (Not data Is Nothing) Then
                dt = CType(data, DataTable)
            Else
                dt = DotNetNuke.Common.ConvertDataReaderToDataTable(db.Profiles_Get(SiteId, -1, UserId))
                DataCache.CacheStore(cachekey, dt)
            End If

            For Each row In dt.Rows
                upi = New UserProfileInfo
                With upi
                    .PortalId = SiteId
                    .UserID = UserId
                    .ModuleId = -1
                    .AdminWatch = Boolean.Parse(row("AdminWatch").ToString)
                    .AnswerCount = Integer.Parse(row("AnswerCount").ToString)
                    .AOL = row("AOL").ToString
                    .AttachDisabled = Boolean.Parse(row("AttachDisabled").ToString)
                    .Avatar = row("Avatar").ToString
                    .AvatarDisabled = Boolean.Parse(row("AvatarDisabled").ToString)
                    .AvatarType = CType(Integer.Parse(row("AvatarType").ToString), AvatarTypes)
                    .Badges = row("Badges").ToString
                    '.Bio = dr("Bio").ToString
                    .DateLastActivity = Date.Parse(row("DateLastActivity").ToString)
                    .DateLastPost = Date.Parse(row("DateLastPost").ToString)
                    .ForumsAllowed = String.Empty
                    .ICQ = row("ICQ").ToString
                    .Interests = row("Interests").ToString
                    .IsUserOnline = CBool(IIf(Integer.Parse(row("IsUserOnline").ToString) = 1, 1, 0))
                    .Location = row("Location").ToString
                    .MSN = row("MSN").ToString
                    .Occupation = row("Occupation").ToString
                    .PrefBlockAvatars = Boolean.Parse(row("PrefBlockAvatars").ToString)
                    .PrefBlockSignatures = Boolean.Parse(row("PrefBlockSignatures").ToString)
                    .PrefDefaultShowReplies = Boolean.Parse(row("PrefDefaultShowReplies").ToString)
                    .PrefDefaultSort = row("PrefDefaultSort").ToString
                    .PrefJumpLastPost = Boolean.Parse(row("PrefJumpLastPost").ToString)
                    .PrefPageSize = Integer.Parse(row("PrefPageSize").ToString)
                    .PrefSubscriptionType = CType(Integer.Parse(row("PrefSubscriptionType").ToString), SubscriptionTypes)
                    .PrefTopicSubscribe = Boolean.Parse(row("PrefTopicSubscribe").ToString)
                    .PrefUseAjax = Boolean.Parse(row("PrefUseAjax").ToString)
                    .ProfileId = Integer.Parse(row("ProfileId").ToString)
                    .ReplyCount = Integer.Parse(row("ReplyCount").ToString)
                    .RewardPoints = Integer.Parse(row("RewardPoints").ToString)
                    .Signature = row("Signature").ToString
                    .SignatureDisabled = Boolean.Parse(row("SignatureDisabled").ToString)
                    .TopicCount = Integer.Parse(row("TopicCount").ToString)
                    .TrustLevel = Integer.Parse(row("TrustLevel").ToString)
                    .UserCaption = row("UserCaption").ToString
                    .ViewCount = Integer.Parse(row("ViewCount").ToString)
                    .WebSite = row("WebSite").ToString
                    .Yahoo = row("Yahoo").ToString
                    .DateCreated = Date.Parse(row("DateCreated").ToString)

                End With
            Next

            Return upi
        End Function
        Friend Function LoadUser(ByVal dnnUser As DotNetNuke.Entities.Users.UserInfo) As User
            Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings()
            Dim u As New User
            Dim cu As DotNetNuke.Entities.Users.UserInfo = dnnUser

            With u
                .UserId = cu.UserID
                .UserName = cu.Username
                .IsSuperUser = cu.IsSuperUser
                .IsAdmin = cu.IsInRole(_portalSettings.AdministratorRoleName)
                .DateCreated = cu.Membership.CreatedDate
                .DateUpdated = cu.Membership.LastActivityDate
                .FirstName = cu.FirstName
                .LastName = cu.LastName
                .DisplayName = cu.DisplayName
                .Email = cu.Email
                .UserRoles = GetRoleIds(cu.Roles, _portalSettings.PortalId) 'RolesToString(cu.Roles)
                If cu.IsSuperUser Then
                    .UserRoles &= Globals.DefaultAnonRoles & _portalSettings.AdministratorRoleId & ";"
                End If
                Dim social As New Social
                .UserRoles &= "|" & cu.UserID & "|" & social.ActiveSocialGroups(cu.UserID, _portalSettings.PortalId) & "|"

                If Not cu.IsSuperUser Then
                    .Properties = GetUserProperties(dnnUser)
                End If

            End With
            Return u
        End Function


        Private Function GetRoleIds(ByVal Roles() As String, ByVal SiteId As Integer) As String
            Dim RoleIds As String = ""
            Dim rc As New DotNetNuke.Security.Roles.RoleController
            For Each r As DotNetNuke.Security.Roles.RoleInfo In rc.GetPortalRoles(SiteId)
                Dim roleName As String = r.RoleName
                For Each role As String In Roles
                    If role <> "" AndAlso Not role Is Nothing Then
                        If roleName = role Then
                            RoleIds &= r.RoleID.ToString & ";"
                            Exit For
                        End If
                    End If
                Next
            Next
            Return RoleIds
        End Function
        Public Function GetUserProperties(ByVal dnnUser As DotNetNuke.Entities.Users.UserInfo) As Hashtable
            Dim ht As New Hashtable
            For Each up As DotNetNuke.Entities.Profile.ProfilePropertyDefinition In dnnUser.Profile.ProfileProperties
                ht.Add(up.PropertyName, up.PropertyValue)
            Next
            Return ht
        End Function
    End Class
End Namespace